 
package com.zdkj.subway.rca.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.zdkj.subway.rca.entity.ViewCkClearOtherAccountReport;
import com.zdkj.subway.rca.mapper.ViewCkClearOtherAccountReportMapper;
import com.zdkj.subway.rca.service.ViewCkClearOtherAccountReportService;
import com.zdkj.subway.rca.util.LocalDateConverter;
import com.zdkj.subway.rca.util.LocalDateTimeConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * VIEW
 *
 * @author stw
 * @date 2021-01-03 17:12:15
 */
@Service
public class ViewCkClearOtherAccountReportServiceImpl extends ServiceImpl<ViewCkClearOtherAccountReportMapper, ViewCkClearOtherAccountReport> implements ViewCkClearOtherAccountReportService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ViewCkClearOtherAccountReportServiceImpl.class);
    @Override
    public List<ViewCkClearOtherAccountReport> listViewCkClearOtherAccountReport(String startDate, String endDate, String operators,String lineCode) {

        List<ViewCkClearOtherAccountReport> list = this.baseMapper.listViewCkClearOtherAccountReport(startDate,endDate,operators,lineCode);
        List<ViewCkClearOtherAccountReport> listNew = new ArrayList<>();

        String operatorsName = null;
        for(ViewCkClearOtherAccountReport obj : list){
            if(!obj.getOperatorsName().equals(operatorsName) && operatorsName != null){
                ViewCkClearOtherAccountReport sum = getSum(operatorsName, list);
                listNew.add(sum);
            }
            operatorsName = obj.getOperatorsName();
            listNew.add(obj);
        }
        if(list.size() > 0) { //最后一个运营商
            ViewCkClearOtherAccountReport sumAll = getSum("合计", list);
            listNew.add(sumAll);
        }
        return listNew;
    }

    private ViewCkClearOtherAccountReport getSum(String operatorsName, List<ViewCkClearOtherAccountReport> list){
        ViewCkClearOtherAccountReport sumViewCkClearOtherAccountReport = new ViewCkClearOtherAccountReport();
        sumViewCkClearOtherAccountReport.setOperatorsName(operatorsName);
        sumViewCkClearOtherAccountReport.setLineName("小计");

        BigDecimal emeTicketRecoveryAmount = new BigDecimal("0");
        BigDecimal emeTicketSaleAmount = new BigDecimal("0");
        BigDecimal emeTicketClearAmount = new BigDecimal("0");
        BigDecimal lpfEmeTicketRecoveryAmount = new BigDecimal("0");
        BigDecimal lpfEmeTicketClearAmount = new BigDecimal("0");
        BigDecimal selfFaultRefundAmount = new BigDecimal("0");
        BigDecimal selfFaultRefundClearAmount = new BigDecimal("0");

        for(ViewCkClearOtherAccountReport  obj : list){
            if(operatorsName.equals("合计") || operatorsName.equals(obj.getOperatorsName())){
                emeTicketRecoveryAmount = emeTicketRecoveryAmount.add(obj.getEmeTicketRecoveryAmount());
                emeTicketSaleAmount = emeTicketSaleAmount.add(obj.getEmeTicketSaleAmount());
                emeTicketClearAmount = emeTicketClearAmount.add(obj.getEmeTicketClearAmount());
                lpfEmeTicketRecoveryAmount = lpfEmeTicketRecoveryAmount.add(obj.getLpfEmeTicketRecoveryAmount());
                lpfEmeTicketClearAmount = lpfEmeTicketClearAmount.add(obj.getLpfEmeTicketClearAmount());
                selfFaultRefundAmount = selfFaultRefundAmount.add(obj.getSelfFaultRefundAmount());
                selfFaultRefundClearAmount = selfFaultRefundClearAmount.add(obj.getSelfFaultRefundClearAmount());
            }
        }

        sumViewCkClearOtherAccountReport.setEmeTicketRecoveryAmount(emeTicketRecoveryAmount);
        sumViewCkClearOtherAccountReport.setEmeTicketSaleAmount(emeTicketSaleAmount);
        sumViewCkClearOtherAccountReport.setEmeTicketClearAmount(emeTicketClearAmount);
        sumViewCkClearOtherAccountReport.setLpfEmeTicketRecoveryAmount(lpfEmeTicketRecoveryAmount);
        sumViewCkClearOtherAccountReport.setLpfEmeTicketClearAmount(lpfEmeTicketClearAmount);
        sumViewCkClearOtherAccountReport.setSelfFaultRefundAmount(selfFaultRefundAmount);
        sumViewCkClearOtherAccountReport.setSelfFaultRefundClearAmount(selfFaultRefundClearAmount);

        return sumViewCkClearOtherAccountReport;
    }

    @Override
    public void export(String startDate,String endDate,String operators,String lineCode,HttpServletResponse response) {

        List<ViewCkClearOtherAccountReport> records = listViewCkClearOtherAccountReport(startDate,endDate,operators,lineCode);
        InputStream excelTemplateIs = null;
        try {
            response.reset(); // 非常重要
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            final String fileName = URLEncoder.encode("人工协议清分对账报表（退换票）", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");

            // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
            // {} 代表普通变量 {.} 代表是list的变量

            excelTemplateIs = this.getClass().getResourceAsStream("/static/excel/template/export/ViewCkClearOtherAccountReportExcelTemplate.xlsx");

            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerConverter(new LocalDateTimeConverter()).registerConverter(new LocalDateConverter()).withTemplate(excelTemplateIs).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("人工协议清分对账报表（退换票）").build();
            // 这里注意 入参用了forceNewRow 代表在写入list的时候不管list下面有没有空行 都会创建一行，然后下面的数据往后移动。默认 是false，会直接使用下一行，如果没有则创建。
            // forceNewRow 如果设置了true,有个缺点 就是他会把所有的数据都放到内存了，所以慎用
            // 简单的说 如果你的模板有list,且list不是最后一行，下面还有数据需要填充 就必须设置 forceNewRow=true 但是这个就会把所有数据放到内存 会很耗内存
            // 如果数据量大 list不是最后一行 参照另一个
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.FALSE).build();
            excelWriter.fill(records, fillConfig, writeSheet);

            excelWriter.finish();

        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("导出人工协议清分对账报表（退换票）异常");
        } finally {
            if(excelTemplateIs != null){
                try {
                    excelTemplateIs.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
    }
}
